package phylacterium.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import phylacterium.beans.LoginBean;
import phylacterium.beans.RegisterBean;
import phylacterium.entities.LoginEntity;
import phylacterium.tools.DBException;
import phylacterium.tools.DBOperations;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private LoginBean bean;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if (session != null && session.getAttribute("userName") != null && session.getAttribute("userId") != null){
			session.invalidate();
			response.sendRedirect("homepage");
			return;
		}
		
		if (bean == null)
			bean = new LoginBean();
		
		request.setAttribute("bean", bean);
		
		bean = null;
		
		ServletContext ctx = this.getServletContext();
		RequestDispatcher dispatcher = ctx
				.getRequestDispatcher("/login.jsp");

		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LoginEntity login = null;
		try{
			login = new LoginEntity(request);
			
			if (login.login.equalsIgnoreCase("")){
				bean = new LoginBean();
				bean.loginError = "Enter login";
				response.sendRedirect("login");
				return;
			}
			if (login.password.equalsIgnoreCase("")){
				bean = new LoginBean();
				bean.loginError = "Enter password";
				bean.login = login.login;
				response.sendRedirect("login");
				return;
			}
			
			if (DBOperations.checkLogin(login)){
				HttpSession session = request.getSession();
				session.setAttribute("userName", login.name);
				session.setAttribute("userId", login.id);
				
				response.sendRedirect("homepage");
				return;
			} else {
				bean = new LoginBean();
				bean.loginError = "Wrong login or password";
				bean.login = login.login;
				response.sendRedirect("login");
				return;
			}
		} catch (DBException e){
			DBException.lastError = e;
			response.sendRedirect("error");
		}
	}

}
